package com.tools.web.interceptor.limiting;

import com.tools.common.object.Note;
import com.tools.common.thread.Timeunit;
import com.tools.db.cache.expiring.ExpiringMap;
import com.tools.web.interceptor.auth.AuthenticationManager;

/**
 * 使用过期 Map 集合 ExpiringMap
 * 来实现限流拦截器
 * */
@Note("使用过期 Map 集合 ExpiringMap 来实现限流拦截器")
public final class ExpiringMapReqLimitInterceptor extends RequestLimitInterceptor {

    private final ExpiringMap<String, Object> cache;

    public ExpiringMapReqLimitInterceptor(ExpiringMap<String, Object> cache, RequestLimitSource source) {
        this(cache, source, null);
    }

    public ExpiringMapReqLimitInterceptor(ExpiringMap<String, Object> cache, RequestLimitSource source,
                                          AuthenticationManager authenticationManager) {
        super(source, cache != null, "本地缓存实例不能为 null", authenticationManager);
        this.cache = cache;
    }

    @Override
    protected Timeunit protected_getImplSelfTimeunit() {
        return Timeunit.MILL;
    }

    @Override
    protected Integer protected_getRequestedCount(String key) {
        return (Integer) this.cache.get(key);
    }

    @Override
    protected void protected_setRequestedCount(String key, int count, long expiration, Timeunit timeunit) {
        this.cache.put(key, count, expiration, timeunit);
    }

    @Override
    protected long protected_getRemainder(String key) {
        return this.cache.getExpectedExpiration(key);
    }

    @Override
    protected void protected_removeRequestCount(String key) {
        this.cache.remove(key);
    }
}
